<template>
  <div class="upload-video-panel">
    <VideoUploader ref="videoUploaderRef"></VideoUploader>
    <div v-if="startUpload" class="video-form">
      <el-form
        :model="formData"
        ref="formDataRef"
        :rules="rules"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="封面" prop="videoCover">
          <imageCoverSelect
            :cover-width="200"
            :cut-width="680"
            :scale="0.6"
            :cover-image="formData.videoCover"
          ></imageCoverSelect>
        </el-form-item>

        <el-form-item label="标题" prop="videoName">
          <el-input
            clearable
            placeholder="请输入标题"
            v-model="formData.videoName"
            :maxlength="100"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <el-form-item label="类型" prop="postType">
          <el-radio-group v-model="formData.postType">
            <el-radio :value="0">自制</el-radio>
            <el-radio :value="1">转载</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="" prop="originfo" v-if="formData.postType == 1">
          <el-input
            clearable
            placeholder="转载视频请注明来源、时间、地点(例：转自https://www.xxx.com/yyyy)，注明来源会更快通过审核哦"
            v-model="formData.originfo"
            :maxlength="200"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <TagInput v-model="formData.tags"></TagInput>
        </el-form-item>

        <el-form-item label="分区" prop="categoryArray">
          <el-cascader
            v-model="formData.categoryArray"
            :options="categoryStore.categoryList"
            :props="{ value: 'categoryId', label: 'categoryIdName' }"
          />
        </el-form-item>

        <el-form-item label="简介" prop="introduction">
          <el-input
            clearable
            placeholder="请填写更全面的相关信息，让更多的人能找到你的视频吧(： "
            type="textarea"
            :rows="5"
            resize="none"
            v-model="formData.introduction"
            :maxlength="2000"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <el-form-item label="互动设置" prop="interaction">
          <el-checkbox-group v-model="formData.interactionArray">
            <el-checkbox value="0">关闭弹幕</el-checkbox>
            <el-checkbox value="1">关闭评论</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">立即投稿</el-button>
          <el-button type="primary" @click="router.push('/ucenter/video')">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import TagInput from './TagInput.vue'
import imageCoverSelect from '@/components/ImageCoverSelect.vue'
import { useCategoryStore } from '@/stores/category'
import VideoUploader from './VideoUploader.vue'
import { useHomeStore } from '@/stores/home'
import { nextTick, onMounted, onUnmounted, provide, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { mitter } from '@/eventbus/eventBus'
import message from '@/utils/message'
import {
  postVideoHttpRequest,
  uploadImageHttpRequest,
  videoByVideoIdInfoHttpRequest,
  type PostVideoDto
} from '@/services/api/video'
type FormData = {
  videoName: string
  postType: number | undefined
  originfo: string
  categoryArray?: number[]
  introduction: string
  interactionArray?: string[] | number[]
  tags: string[]
  videoCover: string
  pcategoryId?: number
  categoryId?: number
}

const route = useRoute()
const router = useRouter()
const homeStore = useHomeStore()
const categoryStore = useCategoryStore()

const startUpload = ref(false)

const formDataRef = ref()

const initialFormData: FormData = {
  videoName: '',
  postType: undefined,
  originfo: '',
  categoryArray: [],
  introduction: '',
  videoCover: '',
  interactionArray: [],
  tags: [],
  pcategoryId: undefined,
  categoryId: undefined
}

const formData = ref<FormData>({ ...initialFormData })

//验证规则
const rules = {
  videoCover: [{ required: true, message: '封面不能为空' }],
  videoName: [{ required: true, message: '标题不能为空' }],
  postType: [{ required: true, message: '类型不能为空' }],
  originfo: [{ required: true, message: '转载说明不能为空' }],
  categoryArray: [{ required: true, message: '分区不能为空' }],
  tags: [{ required: true, message: '标签不能为空' }]
}

const videoUploaderRef = ref()
const videoList = ref([])

//提交投稿
const submitForm = () => {
  //拿到上传的视频文件列表
  const uploadFileList = videoUploaderRef.value.getUploadFileList()
  if (!uploadFileList || uploadFileList.length == 0) {
    message.warning('请上传视频')
    return
  }
  formDataRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return
    }
    let params = {
      uploadFileList: JSON.stringify(uploadFileList),
      ...formData.value,
      pcategoryId: '',
      categoryId: '',
      interaction: ''
    }
    Object.assign(params, formData.value)
    if (params.categoryArray) {
      params.pcategoryId = String(params.categoryArray[0])
      if (params.categoryArray.length > 1) {
        params.categoryId = String(params.categoryArray[1])
      }
    }
    delete params.categoryArray
    if (params.interactionArray) {
      params.interaction = params.interactionArray.join(',')
      delete params.interactionArray
    }
    //判断文件
    if ((params.videoCover as any) instanceof File) {
      const videoCover = await uploadImageHttpRequest({
        file: params.videoCover as any,
        createIsThumbnail: true
      })
      if (!videoCover) {
        return
      }
      params.videoCover = videoCover.data
    }
    const requestData: PostVideoDto = {
      videoName: params.videoName,
      videoCover: params.videoCover,
      pcategoryId: Number(params.pcategoryId),
      categoryId: Number(params.categoryId),
      postType: Number(params.postType),
      tags: params.tags.join(','),
      introduction: params.introduction,
      interaction: params.interaction,
      uploadFileList: params.uploadFileList
    }
    console.log(requestData)

    const res = await postVideoHttpRequest(requestData)
    console.log(res, '发布投稿')

    if (!res) {
      return
    }

    message.success('发布成功')
    router.push('/ucenter/video')
  })
}

mitter.on('startUpload', (fileName) => {
  startUpload.value = true
  //初始化表单
  nextTick(() => {
    formDataRef.value.resetFields()
    formData.value = { ...initialFormData }
    formData.value.tags = []
    formData.value.videoName = fileName as string
  })
})

provide('cutImageCallback', ({ coverImage }: { coverImage: string }) => {
  formData.value.videoCover = coverImage
})

//编辑的时候跳转也是这个路由 点编辑的时候必须是有携带视频ID的
//根据视频ID获取详情然后赋值给表单数据回显 没必要多写一个编辑页面
const init = async () => {
  nextTick(() => {
    videoUploaderRef.value.initUploader(startUpload.value, [])
  })
  if (videoId.value) {
    const res = await videoByVideoIdInfoHttpRequest(videoId.value)
    console.log(res, '根据视频ID获取视频详情')
    if (!res) {
      return
    }
    formData.value = res.data.videoInfoPost as any
    formData.value.tags = String(formData.value.tags).split(',')
    formData.value.categoryArray = []
    if (formData.value.pcategoryId) {
      formData.value.categoryArray.push(formData.value.pcategoryId)
    }
    if (formData.value.categoryId) {
      formData.value.categoryArray.push(formData.value.categoryId)
    }
    formData.value.interactionArray = formData.value.introduction
      ? formData.value.introduction.split(',')
      : []

    nextTick(() => {
      videoUploaderRef.value.initUploader(startUpload.value, res.data.videoInfoFileList)
    })
  }
}

const videoId = ref<string>()
watch(
  () => route.query.videoId,
  (newVal, oldVal) => {
    if (newVal) {
      console.log(newVal, '@@@')

      startUpload.value = true
    } else {
      console.log(newVal, '@@@')
      startUpload.value = false
    }
    videoId.value = newVal as string
    init()
  },
  { immediate: true, deep: true }
)

onUnmounted(() => {
  mitter.off('startUpload')
})
</script>

<style lang="less" scoped></style>
